import { reactive } from "vue";

export type TFormItemType = 'input' | 'select' | 'checkbox'

export interface IFormItem  {
  type: TFormItemType;
  payload: any;
  next: (current: IFormItem, acients: IFormItem[]) => IFormItem | null
  parent: IFormItem | null;
}

const idMapFormItem = new Map<string, IFormItem>();

export function createFormItem(
  type: IFormItem['type'],
  payload: IFormItem['payload'],
  next: IFormItem['next']
): IFormItem {
  const nextFunc: IFormItem['next'] = (current, acients) => {
    // 提供当前item与祖先数组（为用户的提供的next方法“赋能”）=> 时机不对，当前还不是运行时，无法确定祖先，所以不合适
    // 但是运行时构造祖先数组时需要依赖节点的parent属性，这里可以对用户提供的next方法进行“增强”，也就是给next返回的节点确定parent属性值
    const nextItem = next(current, acients);

    // 增强
    if(!nextItem) {
      return null
    }
    nextItem.parent = current;

    // 维护Map<id, item>
    const { id } = current.payload;
    if(id) {
      idMapFormItem.set(id, current);
    }

    return nextItem;
  }
  return reactive({
    type,
    payload,
    next: nextFunc,
    parent: null,
  })
}

export function getAcientById(id: string) {
  return idMapFormItem.get(id);
}
